package cn.wolfcode.service.impl;

import cn.wolfcode.advice.NoLoginException;
import cn.wolfcode.domain.Emp;
import cn.wolfcode.domain.PageBean;
import cn.wolfcode.domain.Result;
import cn.wolfcode.mapper.EmpMapper;
import cn.wolfcode.service.EmpService;
import cn.wolfcode.utils.JwtUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;
    @Override
    public PageBean query(Integer page, Integer pageSize, String name, Integer gender, Date begin, Date end) {
        PageHelper.startPage(page,pageSize);
        List<Emp> emps = empMapper.list(name,gender,begin,end);
        Page<Emp> p =  (Page<Emp>) emps;
        return new PageBean(p.getTotal(),p.getResult());
    }

    @Override
    public void batchDelete(List<Long> ids) {
        empMapper.batchDelete(ids);
    }

    @Override
    public void save(Emp emp) {
        empMapper.save(emp);
    }

    @Override
    public Emp getById(Long id) {
        return empMapper.getById(id);
    }

    @Override
    public void update(Emp emp) {
        empMapper.update(emp);
    }

    @Override
    public Result login(Emp emp) {
      Emp logined =  empMapper.login(emp);
      if(logined!=null){
          //生成jwt
          Map<String,Object> map = new HashMap<>();
          map.put("id",logined.getId());
          map.put("name",logined.getName());
          String string = JwtUtils.generateToken(map);
          return Result.success(string);
      }else{
          throw  new NoLoginException("用户名或密码错误");
      }

//          return Result.error("用户名或密码错误");


    }

}
